package com.service.skySport.impl;

import com.alibaba.fastjson.JSON;
import com.bean.skySport.*;
import com.locators.skySport.HomePage;
import com.locators.skySport.MatchCeterPage;
import com.locators.skySport.PersonCenterPage;
import com.service.skySport.*;
import com.service.webdriver.Browser;
import com.service.webdriver.ElementAction;
import com.utils.Log;
import org.apache.bcel.generic.IF_ACMPEQ;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebElement;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhengshuheng on 2017/9/22.
 */
public class IWebBaseImpl extends Browser implements IWebBase  {
    Log log=new Log(this.getClass());
    public  String login(String userName,String password  ){
        String loginState="";
        setWebDriver();
        driver.manage().timeouts().setScriptTimeout(5, TimeUnit.SECONDS);
        driver.manage().timeouts().pageLoadTimeout(10,TimeUnit.SECONDS);
        try {
            driver.get("http://sky804.com/");
        }catch (TimeoutException e){
            log.info("网页加载过慢,自动跳过等待");
            driver.quit();
            setWebDriver();
            driver.get("http://sky804.com/");
        }

        ElementAction action=new ElementAction();
        if (action.isExistWebMent(HomePage.webcomePageCloseButon,10)){
            log.info("首次进入需要关闭欢迎提示");
            action.findElementAndClick(HomePage.webcomePageCloseButon,10);
        }
        driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);
        driver.manage().timeouts().pageLoadTimeout(15,TimeUnit.SECONDS);
        action.findElement(HomePage.userName,5).sendKeys(userName);
        action.findElementAndClick(HomePage.password1,5);
        action.findElement(HomePage.password2,5).sendKeys(password);
        action.findElementAndClick(HomePage.login,5);
        try {
            driver.switchTo().alert().getText().equals("请正确填写用户名和密码");
            loginState="密码错误！";
        }catch (Exception e){
            try {
                action.findElement(PersonCenterPage.VipCenterLink,5);
                loginState="登录成功";
            }catch (Exception e1){
                loginState="登录失败";
            }

        }

        return loginState;
    }
    public  int getSumPage(){
        enterMatchCenter();
        ElementAction action=new ElementAction();
        driver.switchTo().parentFrame();
        WebElement  frame=action.findElement(MatchCeterPage.matchCenterContentFrame,5);
        driver.switchTo().frame(frame);
        log.info("切換到足球比賽数据frame");
        String sumPageStr=action.getText(MatchCeterPage.lastPageIndex,5);
        if (!sumPageStr.equals("-1")){
            sumPageStr=sumPageStr.replace("[","").replace("]","").replace(" ","");
        }else {
            sumPageStr="1";
        }
        int sumPage=Integer.valueOf(sumPageStr);
        return sumPage;
    }
    public  List<TeamInvest> getSaiShi(int page){
        List<TeamInvest> teamInvestList=new ArrayList<>();
        ElementAction  action=new ElementAction();
        clickPageIndex(page);
        List<WebElement> lsNameList=action.findElements(MatchCeterPage.lsNames);
        log.info("当前页有"+ lsNameList.size()+"场联赛");
        for (int i=0;i<lsNameList.size();i++){
            lsNameList=action.findElements(MatchCeterPage.lsNames);
            String lsName=lsNameList.get(i).getText();
            log.info("进行第"+(i+1)+"场联赛："+lsName+" 信息获取");
            selectALs(lsName);
            Ls ls=new Ls();
            ls.setLsName(lsName);
            List<WebElement> bfList=action.findElements(MatchCeterPage.bfs);//确定有多少行比赛数据

            log.info("当前联赛共有"+bfList.size()+"行比赛数据");
            for (int j=0;j<bfList.size();j++){
                log.info("获取第"+(j+1)+"行比赛数据");
                bfList=action.findElements(MatchCeterPage.bfs);//动态更新比赛数据
                String bf=bfList.get(j).getText();
                GameInfo gameInfo=new GameInfo();
                gameInfo.setMatchTime(bf.split("\n")[0]);
                gameInfo.setScoreA(Integer.valueOf(bf.split("\n")[1].replace(" ","").split("-")[0]));
                gameInfo.setScoreH(Integer.valueOf(bf.split("\n")[1].replace(" ","").split("-")[1]));
                List<WebElement> zkdNameList=action.findElements(MatchCeterPage.zkdNames);
                String zkdName=zkdNameList.get(j).getText();
                Team team =new Team();
                team.setLsName(lsName);
                team.setZdName(zkdName.split("\n")[0]);
                team.setKdName(zkdName.split("\n")[1]);
                for (int k=0;k<4;k++){
                    log.info("获取第"+(k+1)+"盘口数据");
                    PK pk=new PK();
                    switch (k){
                        case 0:
                            zkdNameList=action.findElements(MatchCeterPage.zkdNames);
                            if (zkdNameList.size()>0){
                                String qcPKZdPlLX=action.getText(action.findElements(MatchCeterPage.zkdNames).get(j),"../td[4]/span",5);//全场让球赔率类型-主队--//因元素信息是动态的，不能缓存，所以此处要重新查找一遍
                                String qcPkZdPL=action.getText(action.findElements(MatchCeterPage.zkdNames).get(j),"../td[4]/a",5);//全场让球-主队赔率
                                String qcPKKdPlLX=action.getText(action.findElements(MatchCeterPage.zkdNames).get(j),"../following-sibling::tr[1]/td[2]/span",5);//全场让球-客队赔率类型
                                String qcPkKdPL=action.getText(action.findElements(MatchCeterPage.zkdNames).get(j),"../following-sibling::tr[1]/td[2]/a",5);//全场让球赔率-客队
                                pk.setIsFull("全场");
                                pk.setTeamType("让球盘");
                                pk.setZdPLLX(qcPKZdPlLX);
                                pk.setZdplBD(Float.valueOf(qcPkZdPL));
                                pk.setKdPLLX(qcPKKdPlLX);
                                pk.setKdplBD(Float.valueOf(qcPkKdPL));
                            }else {
                                log.info("该联赛没有足球赛");
                            }
                            break;


                    }

                }
                TeamInvest teamInvest=new TeamInvest();
                teamInvest.setTeam(team);
                teamInvest.setLs(ls);
                teamInvest.setGameInfo(gameInfo);
                teamInvestList.add(teamInvest);

            }



        }


        System.out.println(JSON.toJSONString(teamInvestList));
        return teamInvestList;
    }
    public List<TeamInvest> getSaiShi2(int page){
        List<TeamInvest> teamInvestList=new ArrayList<>();
        ElementAction  action=new ElementAction();
        clickPageIndex(page);
        List<WebElement> lsNameList=action.findElements(MatchCeterPage.lsNames);
        log.info("当前页有"+ lsNameList.size()+"场联赛");
        for (int i=0;i<lsNameList.size();i++){
            lsNameList=action.findElements(MatchCeterPage.lsNames);
            log.info("更新第"+page+"页"+"联赛数量"+lsNameList.size());
            String lsElementXpath=MatchCeterPage.getLsElementXpth(i+1);
            WebElement lsElement=action.findElement(lsElementXpath,5);
            String lsName=lsElement.getText();
            log.info("进行第"+(i+1)+"场联赛："+lsName+" 信息获取");
            log.info("获取当前联赛第1场赛事数据");
            String firstBfXpath=MatchCeterPage.getFirstBfXpath(lsElementXpath);
            TeamInvest firstteamInvest=getFirstTeamInvest(firstBfXpath,lsName,page);
            teamInvestList.add(firstteamInvest);
            String nextBfElementXpath=firstBfXpath;
            for (int j=0;true;j++){
                log.info(" ---获取当前联赛第"+(j+2)+"场赛事数据");
                WebElement webElement=null;
                String nextMatchXpath=MatchCeterPage.getnextMatchXpath(nextBfElementXpath);
                nextBfElementXpath=MatchCeterPage.getNextBfXpath(nextMatchXpath);
                try {
                    TeamInvest teamInvest=getFirstTeamInvest(nextBfElementXpath,lsName,page);
                    teamInvestList.add(teamInvest);
                }catch (Exception e){
                    log.info("当前联赛信息获取完毕");
                    break;
                }

                try {
                    System.out.println("xxxxxx");
                    webElement=action.findElement(nextMatchXpath,5);
                }catch (StaleElementReferenceException e){
                    log.info("下一场元素查找失败重新查找一次");
                    webElement=action.findElement(nextMatchXpath,5);
                }
                if (webElement.findElements(By.xpath("//td")).size()==1){
                    log.info("已是当前最后一场足球比赛，进行下一个联赛数据获取");
                    break;
                }

            }



        }
        System.out.println(JSON.toJSONString(teamInvestList));
        return  teamInvestList;

    }
    public AllowInvestInfoBase queryInvestInfo(TeamInvestBase teamInvestBase){
        return new AllowInvestInfoBase();
    }
    public  String InvestOperate(AllowInvestInfoBase allowInvestInfoBase){
        return "";
    }
    public  List<AllowInvestInfoBase> investResult(){
        return new ArrayList<>();
    }

    /**
     * 进入赛事中心
     * @return
     */
    private void   enterMatchCenter(){
        ElementAction action=new ElementAction();
        try {
            action.findElementAndClick(HomePage.hg_sport,10);
        }catch (Exception e){
            driver.quit();
            login("a66666","1qaz2wsx");
        }

        WebElement frame=action.findElement(MatchCeterPage.matchCenterMainFrame);
        driver.switchTo().frame(frame);
        log.info("切换到赛事中心frame");
        frame=action.findElement(MatchCeterPage.matchCenterHeaderFrame);
        driver.switchTo().frame(frame);
        action.findElementAndClick(MatchCeterPage.gunqiu,5);
        log.info("切换到赛事菜单frame");
        if (action.isExistWebMent(MatchCeterPage.footBallMenu,5)){
            action.findElementAndClick(MatchCeterPage.footBallMenu);
            log.info("点击足球盘口菜单");
        }else {
            log.error("当前没有足球比赛");
        }
    }

    /**
     * 点击页码
     * @param page
     */
    private void clickPageIndex(int page){
        ElementAction action=new ElementAction();
        String pageNow=action.getText(MatchCeterPage.pageNow,5);
        if (!pageNow.equals(String.valueOf(page))&&!pageNow.equals("-1")){
            log.info("当前页不是指定页，需要点击页码");
            String pageNumXpath=MatchCeterPage.getPageNumXpath(page);
            action.findElementAndClick(pageNumXpath,5);
        }else {
            log.info("当前页即为指定页，不需要重复点击");
        }
    }
    private void selectALs(String lsName){
        ElementAction action=new ElementAction();
        //选择一场联赛
        action.findElementAndClick(MatchCeterPage.selectLs,5);//点击选择联赛
        action.findElementAndClick(MatchCeterPage.allNoSelectLsButton,5);//点击全不选按钮
        action.findElementAndClick(MatchCeterPage.selectALsXpath(lsName),5);//选择当前场次联赛
        action.findElementAndClick(MatchCeterPage.lsConfirmButton,5);
        action.sleep(500);
    }


    /**
     * 获取当前联赛第一行团队盘口比赛数据
     * @return
     */
    private TeamInvest getFirstTeamInvest(String bfElementXpath,String lsName,int page){
        ElementAction action=new ElementAction();
        Ls ls=new Ls();
        ls.setLsName(lsName);
        TeamInvest teamInvest=new TeamInvest();
        GameInfo gameInfo=new GameInfo();
        log.info("------开始获取比分数据");
        WebElement  bfElement=action.findElement(bfElementXpath,5);
        String bf=bfElement.getText();
        gameInfo.setMatchTime(bf.split("\n")[0]);
        gameInfo.setScoreA(Integer.valueOf(bf.split("\n")[1].replace(" ","").split("-")[0]));
        gameInfo.setScoreH(Integer.valueOf(bf.split("\n")[1].replace(" ","").split("-")[1]));
        log.info("------获取比分数据成功");
        log.info("------开始获取主客对名");
        WebElement zkdNameElement=action.findElement(MatchCeterPage.getZkdNameXpath(bfElementXpath),5);
        String zkdName=zkdNameElement.getText();
        Team team =new Team();
        team.setLsName(lsName);
        team.setZdName(zkdName.split("\n")[0]);
        team.setKdName(zkdName.split("\n")[1]);
        log.info("------获取主客队名成功");
        List<PK> pkList=getPkList(zkdNameElement);
        teamInvest.setTeam(team);
        teamInvest.setGameInfo(gameInfo);
        teamInvest.setLs(ls);
        teamInvest.setWebPageIndex(page);
        teamInvest.setPkList(pkList);
        log.info("------获取当前场次比赛盘口数据成功");
        return teamInvest;
    }
    /**
     * 获取一行数据的盘口列表
     * @param zkdNameElement
     * @return
     */
    private List<PK> getPkList(WebElement zkdNameElement){
        List<PK> pkList=new ArrayList<>();
        for (int k=0;k<4;k++){
            log.info("获取第"+(k+1)+"盘口数据");
            PK pk=new PK();
            switch (k){
                case 0:
                    pk=getPKForQcRQP(zkdNameElement);
                    break;
                case 1:
                    pk=getPKForQcDXP(zkdNameElement);
                    break;
                case 2:
                    pk=getPKForBcRQP(zkdNameElement);
                    break;
                case 3:
                    pk=getPKForBcDXP(zkdNameElement);
                    break;
            }
            pkList.add(pk);
        }
        return pkList;
    }

    /**
     * 获取全场-让球盘-盘口数据
     * @return
     */
    private PK getPKForQcRQP(WebElement zkdNameElement){
        ElementAction action=new ElementAction();
        PK pk=new PK();
        String qcPKZdPlLX=action.getText(zkdNameElement,"../td[4]/span",5);//全场让球赔率类型-主队--//因元素信息是动态的，不能缓存，所以此处要重新查找一遍
        String qcPkZdPL=action.getText(zkdNameElement,"../td[4]/a",5);//全场让球-主队赔率
        String qcPKKdPlLX=action.getText(zkdNameElement,"../following-sibling::tr[1]/td[2]/span",5);//全场让球-客队赔率类型
        String qcPkKdPL=action.getText(zkdNameElement,"../following-sibling::tr[1]/td[2]/a",5);//全场让球赔率-客队
        pk.setIsFull("全场");
        pk.setTeamType("让球盘");
        pk.setZdPLLX(qcPKZdPlLX);
        pk.setZdplBD(Float.valueOf(qcPkZdPL));
        pk.setKdPLLX(qcPKKdPlLX);
        pk.setKdplBD(Float.valueOf(qcPkKdPL));
        return pk;
    }

    /**
     * 获取全场-大小盘数据
     * @return
     */
    private PK getPKForQcDXP(WebElement zkdNameElement){
        ElementAction action=new ElementAction();
        PK pk=new PK();
        String qcPKZdPlLX=action.getText(zkdNameElement,"../td[5]/span",5);//全场让球赔率类型-主队--//因元素信息是动态的，不能缓存，所以此处要重新查找一遍
        String qcPkZdPL=action.getText(zkdNameElement,"../td[5]/a",5);//全场让球-主队赔率
        String qcPKKdPlLX=action.getText(zkdNameElement,"../following-sibling::tr[1]/td[3]/span",5);//全场让球-客队赔率类型
        String qcPkKdPL=action.getText(zkdNameElement,"../following-sibling::tr[1]/td[3]/a",5);//全场让球赔率-客队
        pk.setIsFull("全场");
        pk.setTeamType("大小盘");
        pk.setZdPLLX(qcPKZdPlLX);
        pk.setZdplBD(Float.valueOf(qcPkZdPL));
        pk.setKdPLLX(qcPKKdPlLX);
        pk.setKdplBD(Float.valueOf(qcPkKdPL));
        return pk;
    }
    /**
     * 获取半场-让球盘数据
     * @return
     */
    private PK getPKForBcRQP(WebElement zkdNameElement){
        ElementAction action=new ElementAction();
        PK pk=new PK();
        String qcPKZdPlLX=action.getText(zkdNameElement,"../td[8]/span",5);//全场让球赔率类型-主队--//因元素信息是动态的，不能缓存，所以此处要重新查找一遍
        String qcPkZdPL=action.getText(zkdNameElement,"../td[8]/a",5);//全场让球-主队赔率
        String qcPKKdPlLX=action.getText(zkdNameElement,"../following-sibling::tr[1]/td[6]/span",5);//全场让球-客队赔率类型
        String qcPkKdPL=action.getText(zkdNameElement,"../following-sibling::tr[1]/td[6]/a",5);//全场让球赔率-客队
        pk.setIsFull("半场");
        pk.setTeamType("让球盘");
        pk.setZdPLLX(qcPKZdPlLX);
        pk.setZdplBD(Float.valueOf(qcPkZdPL));
        pk.setKdPLLX(qcPKKdPlLX);
        pk.setKdplBD(Float.valueOf(qcPkKdPL));
        return pk;
    }
    /**
     * 获取全场-大小盘数据
     * @return
     */
    private PK getPKForBcDXP(WebElement zkdNameElement){
        ElementAction action=new ElementAction();
        PK pk=new PK();
        String qcPKZdPlLX=action.getText(zkdNameElement,"../td[9]/span",5);//全场让球赔率类型-主队--//因元素信息是动态的，不能缓存，所以此处要重新查找一遍
        String qcPkZdPL=action.getText(zkdNameElement,"../td[9]/a",5);//全场让球-主队赔率
        String qcPKKdPlLX=action.getText(zkdNameElement,"../following-sibling::tr[1]/td[7]/span",5);//全场让球-客队赔率类型
        String qcPkKdPL=action.getText(zkdNameElement,"../following-sibling::tr[1]/td[7]/a",5);//全场让球赔率-客队
        pk.setIsFull("半场");
        pk.setTeamType("大小盘");
        pk.setZdPLLX(qcPKZdPlLX);
        pk.setZdplBD(Float.valueOf(qcPkZdPL));
        pk.setKdPLLX(qcPKKdPlLX);
        pk.setKdplBD(Float.valueOf(qcPkKdPL));
        return pk;
    }
    public static void main(String aggs[]){
         IWebBaseImpl iWebBase=new IWebBaseImpl();
        System.out.println(iWebBase.login("a66666","1qaz2wsx"));
        System.out.println("获取比赛总页数"+iWebBase.getSumPage());
        iWebBase.getSaiShi2(2);
        driver.quit();
    }

}
